<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2020/7/3
 * Time: 18:28
 */

namespace App\Logic;


use App\Model\GroupModel;
use App\Model\UserGroupModel;
use App\Services\HelpService;
use App\Services\ReponseCodeService;
use EasySwoole\ORM\DbManager;

class UserGroupLogic
{
    /**获取全部群的哈希
     * @param $userId
     * @return int|array
     */
    public function groupHashAll($userId){
        try{
            $where = array();
            $where['user_id'] = $userId;
            $where['status'] = UserGroupModel::STATUS_NORMAL;
            $groupList = UserGroupModel::create()->where($where)->column('group_id');
            if(empty($groupList)){
                return array();
            }
            foreach ($groupList as $k=>$groupId){
                $group['member_hash'] = $this->groupHash($groupId);
                $group['group_id'] = $groupId;
                $groupList[$k] = $group;
            }
            return $groupList;
        }catch(\Throwable $t){
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }

    /**获取群成员(单个)
     * @param $where
     */
    public function findGroupMember(array $where){
        try{
            return UserGroupModel::create()
                ->where($where)
                ->join('users','user_groups.app_user_id=users.app_user_id','left')
                ->field('user_groups.app_user_id,user_groups.version,user_groups.nickname_in_group,user_groups.status,user_groups.created_at,user_groups.updated_at,user_groups.role,users.app_user_id,users.nickname,users.head');
        }catch(\Throwable $t){
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }
    }


    /**获取群成员哈希
     * @param $groupId
     * @return int|string
     */
   public function groupHash($groupId){
       try{
           $where = array();
           $where['group_id'] = $groupId;
           $where['status'] = UserGroupModel::STATUS_NORMAL;

            $userGroupList = UserGroupModel::create()->order('app_user_id',' asc')->all($where);
            if(empty($userGroupList)){
                return '';
            }
            $str = '';
            foreach ($userGroupList as $userGroup){
                echo  $userGroup['app_user_id'].'####'.$userGroup['version'].PHP_EOL;
                $str = $str.$userGroup['app_user_id'].$userGroup['version'];
            }
            return md5($str);
     }catch(\Throwable $t){
           echo $t->getMessage().PHP_EOL;
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
       }
   }

    /**退出群聊
     * @param $userId用户id
     * @param $groupId群id
     * @return bool|int
     */
    public function leaveGroup($userId,$groupId){
        try{
            DbManager::getInstance()->startTransaction();
            #判断群是否存在
            if(!GroupModel::create()->get(['id'=>$groupId])){
                return ReponseCodeService::CODE_NOT_GROUP_MEMBER;
            }
            #判断是否在群里
            $userGroup = UserGroupModel::create()->get(['group_id'=>$groupId,'user_id'=>$userId]);
            if(empty( $userGroup)){
                return ReponseCodeService::CODE_NOT_GROUP_MEMBER;
            }
            #退出群
            $leaveInfo = [
                'status'=>UserGroupModel::STATUS_DEL,
                'user_id'=>$userId,
                'updated_at'=>HelpService::msectimeToStr(HelpService::msectime())
            ];
            UserGroupModel::create()->update( $leaveInfo,['group_id'=>$groupId,'user_id'=>$userId]);

            #如果是群主，解散群
            if($userGroup['role']==UserGroupModel::ROLE_TYPE_CREATER){
             #删除群
                $updateGroup =
                  ['status'=>GroupModel::STATUS_DEL,
                    'member_count'=>0,
                    'updated_at'=>HelpService::msectimeToStr(HelpService::msectime())
                ];
                #全部群成员更新时间刷新
                $userGroup::create()->update(['status'=>UserGroupModel::STATUS_DEL,'updated_at'=>HelpService::msectimeToStr(HelpService::msectime())],['group_id'=>$groupId]);
            }else{
                $memberCount = UserGroupModel::create()->where(['group_id'=>$groupId,'status'=>UserGroupModel::STATUS_NORMAL])->count();
                $updateGroup =
                    [
                        'member_count'=>$memberCount,
                        'updated_at'=>HelpService::msectimeToStr(HelpService::msectime())
                    ];
            }
            GroupModel::create()->update($updateGroup,['id'=>$groupId]);
        }catch(\Throwable $t){
         
            return ReponseCodeService::CODE_SERVICE_UNAVAILABLE;
        }finally {
            //提交事务

            DbManager::getInstance()->commit();
        }


        return ReponseCodeService::CODE_OK;
    }
}